package com.cmc6.param.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmc6.common.constant.BaseConstant;
import com.cmc6.common.exception.BaseBizCodeEnum;
import com.cmc6.common.mapper.ParamMapper;
import com.cmc6.common.model.dto.NotEmptyIdSet;
import com.cmc6.common.model.dto.NotNullId;
import com.cmc6.common.model.entity.BaseEntityThree;
import com.cmc6.common.model.entity.BaseEntityTwo;
import com.cmc6.common.model.entity.ParamDO;
import com.cmc6.common.util.ApiResult;
import com.cmc6.common.util.ParamUtil;
import com.cmc6.param.model.dto.ParamInsertOrUpdateDTO;
import com.cmc6.param.model.dto.ParamPageDTO;
import com.cmc6.param.service.ParamService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ParamServiceImpl extends ServiceImpl<ParamMapper, ParamDO> implements ParamService {

    /**
     * 新增/修改 系统参数
     */
    @Override
    @Transactional
    public String insertOrUpdate(ParamInsertOrUpdateDTO dto) {

        ParamDO entity = BeanUtil.copyProperties(dto, ParamDO.class);

        saveOrUpdate(entity);

        ParamUtil.deleteRedisCache(); // 移除 redis中【系统参数】的缓存

        return BaseBizCodeEnum.API_RESULT_OK.getMsg();
    }

    /**
     * 分页排序查询：系统参数
     */
    @Override
    public Page<ParamDO> myPage(ParamPageDTO dto) {

        return lambdaQuery().like(StrUtil.isNotBlank(dto.getName()), ParamDO::getName, dto.getName())
            .like(StrUtil.isNotBlank(dto.getRemark()), BaseEntityThree::getRemark, dto.getRemark())
            .eq(dto.getId() != null, BaseEntityTwo::getId, dto.getId())
            .eq(dto.getEnableFlag() != null, BaseEntityThree::getEnableFlag, dto.getEnableFlag()).page(dto.getPage());

    }

    /**
     * 通过主键id，查看详情
     */
    @Override
    public ParamDO infoById(NotNullId notNullId) {
        return getById(notNullId.getId());
    }

    /**
     * 删除系统参数
     */
    @Override
    @Transactional
    public String deleteByIdSet(NotEmptyIdSet notEmptyIdSet) {

        if (notEmptyIdSet.getIdSet().contains(BaseConstant.USER_MUTUALLY_EXCLUSIVE_ID)) {
            ApiResult.error("操作失败：id【" + BaseConstant.USER_MUTUALLY_EXCLUSIVE_ID + "】不允许删除");
        }

        if (notEmptyIdSet.getIdSet().contains(BaseConstant.RSA_PRIVATE_KEY_ID)) {
            ApiResult.error("操作失败：id【" + BaseConstant.RSA_PRIVATE_KEY_ID + "】不允许删除");
        }

        if (notEmptyIdSet.getIdSet().contains(BaseConstant.IP_REQUESTS_PER_SECOND_ID)) {
            ApiResult.error("操作失败：id【" + BaseConstant.IP_REQUESTS_PER_SECOND_ID + "】不允许删除");
        }

        removeByIds(notEmptyIdSet.getIdSet());

        ParamUtil.deleteRedisCache(); // 移除 redis中【系统参数】的缓存

        return BaseBizCodeEnum.API_RESULT_OK.getMsg();

    }
}




